package com.ganzalang.gmall.learning.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @description: Scattering：将数据写入到Buffer时，可以采用buffer数组，依次写入[分散]；Gathering：从buffer读取数据时，可以采用buffer数组，依次读取
 * @author: Ganzalang
 * @Date 2021/7/13 20:19
 */
@Slf4j
public class ScattingAndGatheringTest {

    public static void main(String[] args) throws Exception{

        // 使用ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        // 绑定端口号并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        // 创建Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 从客户端接收的最大字节
        int messageLength = 8;
        // 循环读取
        while (true) {
            int byteRead = 0;

            while (byteRead < messageLength) {
                // 将socket通道中的数据写到buffer中
                long readLenth = socketChannel.read(byteBuffers);
                // 累计读取的个数
                byteRead += readLenth;
                log.info("byteRead=" + byteRead);
                // 使用流打印，查看当前的buffer的position以及limit
                Arrays.asList(byteBuffers).stream().map(buffer -> "position=" + buffer.position() + ", limit=" + buffer.limit()).forEach(System.out::println);

                // 将所有的buffer进行flip
                Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());

                // 将数据回显给客户端
                long byteWrite = 0;
                while (byteWrite < messageLength) {
                    long writeLength = socketChannel.write(byteBuffers);
                    byteWrite += writeLength;
                }

                // 将所有buffer clear
                Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());

                log.info("byteRead={}, byteWrite={}, messageLenth={}", byteRead, byteWrite, messageLength);

            }
        }

    }
}
